package edu.gj.demo;

import com.google.gson.Gson;
import org.json.JSONObject;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 * @author Simple
 * @date 2020/4/16 13:55
 */
public class Client {

    public static void main(String[] args) throws IOException {


        Socket socket = new Socket("localhost", 8080);
        final PrintStream printStream = new PrintStream(new BufferedOutputStream(socket.getOutputStream()));
        final BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        MessageBean messageBean = new MessageBean();
        messageBean.setType(1);
        messageBean.setUserName("client");
        printStream.println(new Gson().toJson(messageBean));
        printStream.flush();
        new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < Integer.MAX_VALUE; i++) {
                    try {
                        Thread.sleep(2 * 60 * 1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    MessageBean messageBean = new MessageBean();
                    messageBean.setType(0);
                    messageBean.setContent("心跳消息");
                    printStream.println(new Gson().toJson(messageBean));
                    printStream.flush();
                }
            }
        }).start();

        new Thread(new Runnable() {
            public void run() {
                while (true) {
                    try {
                        String message = reader.readLine();
                        MessageBean messageBean = new Gson().fromJson(message, MessageBean.class);
                        if (messageBean.getType() == 2) {
                            //系统分发：
                            System.out.println("系统消息：" + messageBean.getContent());
                        } else if (messageBean.getType() == 3) {
                            //点对点消息
                            System.out.println("收到来自：" + messageBean.getSender() + "的消息：" + messageBean.getContent());
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        return;
                    }
                }
            }
        }).start();


        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            MessageBean messageBeanSend = new MessageBean();
            messageBeanSend.setType(3);
            messageBeanSend.setContent(scanner.nextLine());
            messageBeanSend.setSender("client");
            messageBeanSend.setTo("client2");
            printStream.println(new Gson().toJson(messageBeanSend));
            printStream.flush();
        }

    }


}
